<template>
  <div class="activity-detail-container" v-loading="loading">
    <div v-if="activity.id" class="activity-content">
      <div class="activity-header">
        <h1 class="activity-title">{{ activity.name }}</h1>
        <div class="activity-status">
          <el-tag :type="getStatusType(activity.status)">{{ getStatusText(activity.status) }}</el-tag>
        </div>
      </div>
      
      <div class="activity-banner">
        <img :src="activity.imageUrl || 'https://picsum.photos/id/42/1200/400'" alt="活动封面" />
      </div>
      
      <div class="activity-info-section">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-card class="info-card">
              <template #header>
                <div class="card-header">
                  <span>活动信息</span>
                </div>
              </template>
              <div class="activity-info">
                <div class="info-item">
                  <span class="label">活动类型:</span>
                  <span class="value">{{ activity.typeName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">活动地点:</span>
                  <span class="value">{{ activity.location }}</span>
                </div>
                <div class="info-item">
                  <span class="label">活动时间:</span>
                  <span class="value">{{ formatDateTime(activity.startTime) }} - {{ formatDateTime(activity.endTime) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">活动时长:</span>
                  <span class="value">{{ activity.duration }}小时</span>
                </div>
                <div class="info-item">
                  <span class="label">报名人数:</span>
                  <span class="value">{{ activity.registeredNumber }}/{{ activity.totalNumber }}</span>
                </div>
                <div class="info-item">
                  <span class="label">报名截止:</span>
                  <span class="value">{{ formatDateTime(activity.registrationDeadline) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">组织单位:</span>
                  <span class="value">{{ activity.organizationName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">负责人:</span>
                  <span class="value">{{ activity.leaderName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">联系方式:</span>
                  <span class="value">{{ activity.contactInfo }}</span>
                </div>
              </div>
            </el-card>
            
            <el-card class="description-card">
              <template #header>
                <div class="card-header">
                  <span>活动详情</span>
                </div>
              </template>
              <div class="activity-description" v-html="activity.description"></div>
            </el-card>
            
            <el-card class="evaluation-card" v-if="activity.status === 4">
              <template #header>
                <div class="card-header">
                  <span>活动评价</span>
                  <el-button v-if="!userEvaluation && isRegistered" type="primary" size="small" @click="showEvaluationDialog">写评价</el-button>
                </div>
              </template>
              <div v-if="evaluations.length > 0" class="evaluation-list">
                <div v-for="(item, index) in evaluations" :key="index" class="evaluation-item">
                  <div class="evaluation-header">
                    <div class="user-info">
                      <el-avatar :size="40" :src="item.avatar"></el-avatar>
                      <div class="user-details">
                        <div class="username">{{ item.username }}</div>
                        <div class="date">{{ formatDateTime(item.createTime) }}</div>
                      </div>
                    </div>
                    <div class="rating">
                      <el-rate v-model="item.rating" disabled text-color="#ff9900"></el-rate>
                    </div>
                  </div>
                  <div class="evaluation-content">{{ item.content }}</div>
                </div>
              </div>
              <div v-else class="empty-evaluation">
                <el-empty description="暂无评价"></el-empty>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="8">
            <el-card class="action-card">
              <div class="action-section">
                <div class="registration-status">
                  <h3>报名状态</h3>
                  <div class="status-text" :class="{'status-registered': isRegistered}">
                    {{ isRegistered ? '已报名' : '未报名' }}
                  </div>
                </div>
                
                <div class="action-buttons">
                  <el-button 
                    v-if="activity.status === 1 && !isRegistered" 
                    type="primary" 
                    :disabled="activity.registeredNumber >= activity.totalNumber"
                    @click="handleRegister"
                  >立即报名</el-button>
                  <el-button 
                    v-if="isRegistered && (activity.status === 0 || activity.status === 1 || activity.status === 2)" 
                    type="danger" 
                    @click="handleCancelRegistration"
                  >取消报名</el-button>
                  <el-button 
                    :type="isCollected ? 'warning' : 'info'" 
                    @click="toggleCollection"
                  >
                    <el-icon><Star /></el-icon>
                    <span>{{ isCollected ? '已收藏' : '收藏' }}</span>
                  </el-button>
                  <el-button 
                    v-if="isRegistered && activity.status === 3" 
                    type="success" 
                    :disabled="isCheckedIn"
                    @click="handleCheckIn"
                  >{{ isCheckedIn ? '已签到' : '签到' }}</el-button>
                </div>
              </div>
              
              <el-divider />
              
              <div class="countdown-section" v-if="activity.status === 1 || activity.status === 2">
                <h3>{{ activity.status === 1 ? '距离报名截止' : '距离活动开始' }}</h3>
                <div class="countdown">
                  <div class="time-block">
                    <div class="time">{{ countdown.days }}</div>
                    <div class="label">天</div>
                  </div>
                  <div class="separator">:</div>
                  <div class="time-block">
                    <div class="time">{{ countdown.hours }}</div>
                    <div class="label">时</div>
                  </div>
                  <div class="separator">:</div>
                  <div class="time-block">
                    <div class="time">{{ countdown.minutes }}</div>
                    <div class="label">分</div>
                  </div>
                  <div class="separator">:</div>
                  <div class="time-block">
                    <div class="time">{{ countdown.seconds }}</div>
                    <div class="label">秒</div>
                  </div>
                </div>
              </div>
              
              <el-divider />
              
              <div class="activity-stats">
                <div class="stat-item">
                  <div class="stat-label">收藏人数</div>
                  <div class="stat-value">{{ stats.collectionCount }}</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">报名人数</div>
                  <div class="stat-value">{{ activity.registeredNumber }}/{{ activity.totalNumber }}</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">浏览次数</div>
                  <div class="stat-value">{{ stats.viewCount }}</div>
                </div>
              </div>
            </el-card>
            
            <el-card class="related-card">
              <template #header>
                <div class="card-header">
                  <span>相关活动</span>
                </div>
              </template>
              <div v-if="relatedActivities.length > 0" class="related-list">
                <div v-for="(item, index) in relatedActivities" :key="index" class="related-item" @click="goToActivity(item.id)">
                  <div class="related-image">
                    <img :src="item.imageUrl || 'https://picsum.photos/id/45/200/100'" :alt="item.name" />
                  </div>
                  <div class="related-info">
                    <div class="related-title">{{ item.name }}</div>
                    <div class="related-date">{{ formatDateTime(item.startTime) }}</div>
                  </div>
                </div>
              </div>
              <div v-else class="empty-related">
                <el-empty description="暂无相关活动"></el-empty>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
    
    <div v-else-if="!loading" class="empty-activity">
      <el-empty description="未找到活动信息"></el-empty>
      <el-button type="primary" @click="$router.push('/activity/list')">返回活动列表</el-button>
    </div>
    
    <!-- 评价对话框 -->
    <el-dialog v-model="evaluationDialogVisible" title="活动评价" width="500px">
      <el-form :model="evaluationForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate v-model="evaluationForm.rating" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"></el-rate>
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input
            v-model="evaluationForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评价内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="evaluationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEvaluation">提交评价</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getActivity, getRecommendActivities } from '@/api/activity';
import { registerActivity, cancelRegistration, isUserRegistered, checkIn } from '@/api/registration';
import { addCollection, cancelCollection, isUserCollected, countActivityCollections } from '@/api/collection';
import { createEvaluation, getActivityEvaluations, isUserEvaluated, getUserEvaluation } from '@/api/evaluation';
import { formatDateTime } from '@/utils/format';
import { Star } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

const activityId = computed(() => route.params.id);
const loading = ref(false);

// 活动详情
const activity = ref({});

// 报名、收藏、签到状态
const isRegistered = ref(false);
const isCollected = ref(false);
const isCheckedIn = ref(false);

// 相关活动
const relatedActivities = ref([]);

// 活动评价
const evaluations = ref([]);
const userEvaluation = ref(null);
const evaluationDialogVisible = ref(false);
const evaluationForm = reactive({
  rating: 5,
  content: ''
});

// 活动统计
const stats = reactive({
  collectionCount: 0,
  viewCount: 0
});

// 倒计时
const countdown = reactive({
  days: '00',
  hours: '00',
  minutes: '00',
  seconds: '00'
});
let countdownTimer = null;

// 获取活动详情
const getActivityDetail = async () => {
  try {
    loading.value = true;
    const response = await getActivity(activityId.value);
    activity.value = response.data;
    
    // 检查用户是否已报名和收藏活动
    const [registrationRes, collectionRes] = await Promise.all([
      isUserRegistered(activityId.value),
      isUserCollected(activityId.value)
    ]);
    isRegistered.value = registrationRes.data;
    isCollected.value = collectionRes.data;
    
    // 获取活动收藏数
    const collectionsRes = await countActivityCollections(activityId.value);
    stats.collectionCount = collectionsRes.data;
    
    // 模拟浏览次数
    stats.viewCount = Math.floor(Math.random() * 1000) + 100;
    
    // 获取活动评价
    if (activity.value.status === 4) {
      await getEvaluations();
    }
    
    // 获取相关活动推荐
    getRelatedActivities();
    
    // 设置倒计时
    if (activity.value.status === 1 || activity.value.status === 2) {
      startCountdown();
    }
  } catch (error) {
    console.error('获取活动详情失败', error);
    ElMessage.error('获取活动详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取活动评价列表
const getEvaluations = async () => {
  try {
    const response = await getActivityEvaluations(activityId.value, 1, 1, 10);
    evaluations.value = response.data.records || [];
    
    // 检查用户是否已评价
    if (isRegistered.value) {
      const evaluatedRes = await isUserEvaluated(activityId.value);
      if (evaluatedRes.data) {
        const userEvalRes = await getUserEvaluation(activityId.value);
        userEvaluation.value = userEvalRes.data;
      }
    }
  } catch (error) {
    console.error('获取活动评价失败', error);
  }
};

// 获取相关活动
const getRelatedActivities = async () => {
  try {
    const response = await getRecommendActivities();
    // 排除当前活动
    relatedActivities.value = response.data.filter(item => item.id !== parseInt(activityId.value)).slice(0, 3);
  } catch (error) {
    console.error('获取相关活动失败', error);
  }
};

// 报名活动
const handleRegister = async () => {
  try {
    await registerActivity(activityId.value);
    isRegistered.value = true;
    activity.value.registeredNumber += 1;
    ElMessage.success('报名成功');
  } catch (error) {
    console.error('报名失败', error);
    ElMessage.error(error.message || '报名失败');
  }
};

// 取消报名
const handleCancelRegistration = async () => {
  try {
    await ElMessageBox.confirm('确定要取消报名吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await cancelRegistration(activityId.value);
    isRegistered.value = false;
    activity.value.registeredNumber -= 1;
    ElMessage.success('已取消报名');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消报名失败', error);
      ElMessage.error(error.message || '取消报名失败');
    }
  }
};

// 切换收藏状态
const toggleCollection = async () => {
  try {
    if (isCollected.value) {
      await cancelCollection(activityId.value);
      isCollected.value = false;
      stats.collectionCount -= 1;
      ElMessage.success('已取消收藏');
    } else {
      await addCollection(activityId.value);
      isCollected.value = true;
      stats.collectionCount += 1;
      ElMessage.success('收藏成功');
    }
  } catch (error) {
    console.error('操作失败', error);
    ElMessage.error(error.message || '操作失败');
  }
};

// 签到
const handleCheckIn = async () => {
  try {
    await checkIn(activityId.value);
    isCheckedIn.value = true;
    ElMessage.success('签到成功');
  } catch (error) {
    console.error('签到失败', error);
    ElMessage.error(error.message || '签到失败');
  }
};

// 显示评价对话框
const showEvaluationDialog = () => {
  evaluationDialogVisible.value = true;
  if (userEvaluation.value) {
    evaluationForm.rating = userEvaluation.value.rating;
    evaluationForm.content = userEvaluation.value.content;
  }
};

// 提交评价
const submitEvaluation = async () => {
  if (!evaluationForm.content.trim()) {
    ElMessage.warning('请输入评价内容');
    return;
  }
  
  try {
    const data = {
      activityId: activityId.value,
      rating: evaluationForm.rating,
      content: evaluationForm.content
    };
    
    await createEvaluation(data);
    evaluationDialogVisible.value = false;
    
    // 刷新评价列表
    await getEvaluations();
    
    ElMessage.success('评价提交成功');
  } catch (error) {
    console.error('评价提交失败', error);
    ElMessage.error(error.message || '评价提交失败');
  }
};

// 前往活动详情
const goToActivity = (id) => {
  router.push(`/activity/detail/${id}`);
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 规划中
    1: 'success', // 报名中
    2: 'warning', // 等待中
    3: 'primary', // 进行中
    4: 'danger'   // 已结束
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '规划中',
    1: '报名中',
    2: '等待中',
    3: '进行中',
    4: '已结束'
  };
  return statusMap[status] || '未知';
};

// 启动倒计时
const startCountdown = () => {
  const updateCountdown = () => {
    const targetDate = activity.value.status === 1 
      ? new Date(activity.value.registrationDeadline)
      : new Date(activity.value.startTime);
    
    const now = new Date();
    const diff = targetDate - now;
    
    if (diff <= 0) {
      clearInterval(countdownTimer);
      countdown.days = '00';
      countdown.hours = '00';
      countdown.minutes = '00';
      countdown.seconds = '00';
      return;
    }
    
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);
    
    countdown.days = days < 10 ? `0${days}` : days.toString();
    countdown.hours = hours < 10 ? `0${hours}` : hours.toString();
    countdown.minutes = minutes < 10 ? `0${minutes}` : minutes.toString();
    countdown.seconds = seconds < 10 ? `0${seconds}` : seconds.toString();
  };
  
  updateCountdown();
  countdownTimer = setInterval(updateCountdown, 1000);
};

onMounted(() => {
  getActivityDetail();
});

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style lang="scss" scoped>
.activity-detail-container {
  padding: 20px;
  
  .activity-content {
    .activity-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .activity-title {
        margin: 0;
        font-size: 24px;
        font-weight: bold;
      }
      
      .activity-status {
        .el-tag {
          font-size: 14px;
          padding: 0 10px;
          height: 28px;
          line-height: 28px;
        }
      }
    }
    
    .activity-banner {
      margin-bottom: 30px;
      border-radius: 8px;
      overflow: hidden;
      height: 300px;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .activity-info-section {
      .info-card {
        margin-bottom: 20px;
        
        .activity-info {
          .info-item {
            margin-bottom: 15px;
            display: flex;
            
            .label {
              width: 100px;
              color: #606266;
              font-weight: bold;
            }
            
            .value {
              flex: 1;
              color: #303133;
            }
          }
        }
      }
      
      .description-card {
        margin-bottom: 20px;
        
        .activity-description {
          line-height: 1.8;
          color: #303133;
        }
      }
      
      .evaluation-card {
        .evaluation-list {
          .evaluation-item {
            padding: 15px 0;
            border-bottom: 1px solid #ebeef5;
            
            &:last-child {
              border-bottom: none;
            }
            
            .evaluation-header {
              display: flex;
              justify-content: space-between;
              margin-bottom: 10px;
              
              .user-info {
                display: flex;
                align-items: center;
                
                .user-details {
                  margin-left: 10px;
                  
                  .username {
                    font-weight: bold;
                    font-size: 14px;
                  }
                  
                  .date {
                    font-size: 12px;
                    color: #909399;
                    margin-top: 5px;
                  }
                }
              }
            }
            
            .evaluation-content {
              color: #303133;
              line-height: 1.6;
            }
          }
        }
      }
      
      .action-card {
        margin-bottom: 20px;
        
        .action-section {
          .registration-status {
            text-align: center;
            margin-bottom: 20px;
            
            h3 {
              margin: 0 0 10px;
              color: #606266;
            }
            
            .status-text {
              font-size: 18px;
              font-weight: bold;
              color: #909399;
              
              &.status-registered {
                color: #67c23a;
              }
            }
          }
          
          .action-buttons {
            display: flex;
            flex-direction: column;
            gap: 10px;
          }
        }
        
        .countdown-section {
          text-align: center;
          
          h3 {
            margin: 0 0 15px;
            color: #606266;
          }
          
          .countdown {
            display: flex;
            justify-content: center;
            align-items: center;
            
            .time-block {
              display: flex;
              flex-direction: column;
              align-items: center;
              
              .time {
                background-color: #f5f7fa;
                border-radius: 4px;
                padding: 5px 10px;
                font-size: 20px;
                font-weight: bold;
                color: #409eff;
                min-width: 40px;
                text-align: center;
              }
              
              .label {
                font-size: 12px;
                color: #909399;
                margin-top: 5px;
              }
            }
            
            .separator {
              margin: 0 5px;
              font-size: 20px;
              font-weight: bold;
              color: #409eff;
            }
          }
        }
        
        .activity-stats {
          display: flex;
          justify-content: space-between;
          
          .stat-item {
            text-align: center;
            
            .stat-label {
              font-size: 14px;
              color: #909399;
              margin-bottom: 5px;
            }
            
            .stat-value {
              font-size: 18px;
              font-weight: bold;
              color: #409eff;
            }
          }
        }
      }
      
      .related-card {
        .related-list {
          .related-item {
            display: flex;
            margin-bottom: 15px;
            cursor: pointer;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .related-image {
              width: 80px;
              height: 60px;
              border-radius: 4px;
              overflow: hidden;
              margin-right: 10px;
              
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
            
            .related-info {
              flex: 1;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              
              .related-title {
                font-size: 14px;
                font-weight: bold;
                color: #303133;
                
                &:hover {
                  color: #409eff;
                }
              }
              
              .related-date {
                font-size: 12px;
                color: #909399;
              }
            }
          }
        }
      }
    }
  }
  
  .empty-activity {
    text-align: center;
    padding: 100px 0;
    
    .el-button {
      margin-top: 20px;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style> 